"this" Keyword Explained
The this keyword is one of the most important concepts in JavaScript. It is commonly asked in interviews and used in real projects.
What is this?
this refers to the current object in which it is used.
In simple words, it points to the object that is calling the function.
Real-Life Example Idea
Think like this:
If you are in a room, and you say “this room”, you mean the current room you are in.
Same way in JavaScript, this means the current object you are working with.
Object Example
We create two objects:
userobject (main object)addressobject (extra details)
Code Explanation
User Object
let user = {
name: "anil",
age: 29,
moreDetails: function () {
console.log("hello, my name is " + this.name + ", my house no is " + address.houseNo);
}
}
Address Object
let address = {
houseNo: 663,
city: "gurgaon"
}
Calling Function
user.moreDetails();
Output Logic
When we call:
user.moreDetails()
What happens:
this.namerefers touser.name- So it prints
"anil" address.houseNois accessed directly from another object
Important Concept
Inside an object method:
thisrefers to the object that calls the function- Here,
thisrefers touser
So:
this.name → user.name
Final Output
hello, my name is anil, my house no is 663